package nil.ed.simulator.request.ui.jfx.ui.table;

import lombok.Getter;
import lombok.SneakyThrows;
import nil.ed.simulator.request.ui.jfx.ui.table.annotation.TableColumn;
import nil.ed.simulator.request.ui.jfx.ui.table.annotation.TableConfig;

import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;

/**
 * @author lidelin.
 */
public class TableModelContext {

    @Getter
    private Class<?> clazz;

    @Getter
    private List<ColumnConfig> columnConfigs;

    @Getter
    private TableCallback tableCallback;

    public TableModelContext(Class<?> clazz) {
        this.clazz = clazz;
        this.columnConfigs = initColumnConfigs(clazz);
    }

    @SneakyThrows
    private List<ColumnConfig> initColumnConfigs(Class<?> modelClazz) {
        Field[] fields = modelClazz.getDeclaredFields();
        List<ColumnConfig> configs = new LinkedList<>();
        for (Field f : fields) {
            TableColumn tableColumn = f.getAnnotation(TableColumn.class);
            if (tableColumn != null) {
                f.trySetAccessible();
                ColumnConfig columnConfig = new ColumnConfig()
                        .setField(f)
                        .setTitle(tableColumn.value());
                configs.add(columnConfig);
            }
        }
        TableConfig tableConfig = modelClazz.getAnnotation(TableConfig.class);
        if (tableConfig != null) {
            Class<? extends TableCallback> callbackType = tableConfig.callback();
            TableCallback callback = callbackType.getDeclaredConstructor().newInstance();
            this.tableCallback = callback;
        }
        return configs;
    }
}
